#!/usr/bin/perl

#Daemon dummy script

use lib 'mods';
use Util::Logger;
use forker;
use ExploitFarm_SQL;
use db_config;

our $getters_dir='getters';
our $templates='templates';

sub get_conf_teams
{
    $db->connect();
    return $db->get_teams();
}

sub make_exploits_diff
{
    my ($dir,$expl)=@_;
    my $fdir;
    my $t;
    my %expl=%$expl;

    map {$expl{$_}=0;} keys %expl;

    opendir $fdir,$dir or die "Can't open exploits dir '$dir' : $!\n";
    while ($t=readdir($fdir))
    {
	next if ((!-d "$dir/$t") or (-f "$dir/$t/stop.txt") or ($t=~/^(?:$templates|\..*)$/c));
	($expl{$t}=2,next) if (!exists($expl{$t}));
	($expl{$t}=1,next) if ($expl{$t}==0);
	#0 - exploit to stop
	#1 - do not touch (already running and no need to stop)
	#2 - start (new exploit)
    }
    closedir $fdir;
    return \%expl;
}

sub stop_exploit
{
    my $exploit=shift;
    $l->info("Stop exploit '$exploit'\n");
    my $forker=$exploits{$exploit};
    $forker->stop();
    delete $exploits{$exploit};
}

sub do_nothing
{
    my $exploit=shift;
}

sub start_exploit
{
    my $exploit=shift;
    $l->info("Start exploit '$exploit'\n");
    my $teams=get_conf_teams();
    if (!defined $$teams[0])
    {
	$l->error("$exploit NOT STARTED: error while getting teams: $$teams[1]");
	return $$teams[1];
    }
    my %conf=
	(
	    exploit		=> "$exploit",
	    exploit_dir		=> "$getters_dir/$exploit",
	    teams		=> $teams,
	    global_log		=> $l,
	);
    my $forker=new forker(%conf);
    $forker->run();
    $exploits{$exploit}=$forker;
}

our %cmd=
    (
	0 => \&stop_exploit,
	1 => \&do_nothing,
	2 => \&start_exploit,
    );

sub make_no_difference
{
    my $diff=shift;
    for (keys %$diff)
    {
	my $cmd=$cmd{$$diff{$_}};
	$cmd->($_) if (defined $cmd);
    }
}

our $db=new ExploitFarm_SQL($db_host,$db_port,$db_name,$db_login,$db_pass);
our $l=new Util::Logger("$getters_dir/global_log.txt");

while (1)
{
    my $diff=make_exploits_diff($getters_dir,\%exploits);
    map {print "$_\t\t$$diff{$_}\n";} keys %$diff;
    make_no_difference($diff);
    print "---\n";

    open F,">$getters_dir/running.txt";
    map {print F "$_\n";} keys %exploits;
    close F;

    sleep 3;
}
